from instance.app_instance import app
from instance.celery_instance import celery
from celery.result import AsyncResult

import json

from flask import request

@app.route('/api/v1/task/commit/<task_name>')
def commit_task(task_name):
    task_id = ''
    if task_name in app.tasks:
        param = {}
        if len(request.data) > 0:
            param = json.loads(request.data)
        task_id = app.tasks[task_name].delay(param).task_id
    return '{ "task_id": %s}' % task_id, 200

@app.route('/api/v1/task/progress/<task_id>')
def get_task_progress(task_id):
    pecentage = 0
    result = AsyncResult(task_id, app=celery)
    if result.ready():
        pecentage = 100
    if result.state == self.progress_state:
        meta = result.info
        pecentage = float(meta['current']) / float(meta['total']) * 100
    return '{ "pecentage": %s}' % pecentage, 200